<template>
  <div class="app-container">
    <!-- 搜索头部 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品编号" prop="proCode">
        <el-input
          v-model="queryParams.proCode"
          placeholder="请输入商品编号"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="proName">
        <el-input
          v-model="queryParams.proName"
          placeholder="请输入商品名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="typeId">
        <el-select
          v-model="queryParams.typeId"
          clearable
          placeholder="请选择商品分类"
        >
          <el-option
            :label="type.typeName"
            :value="type.id"
            v-for="type in typeList"
            :key="type.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker
          v-model="daterangeModifyDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 中部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basedata:goods:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basedata:goods:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basedata:goods:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- 中部数据 -->
    <el-table
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="70" align="center" fixed="left">
        <template slot-scope="scope">
          {{
            scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="商品编号"
        align="center"
        prop="proCode"
        fixed="left"
        width="200"
      >
        <template slot-scope="scope">
          <el-link @click="showGoodsInfo(scope.row)" type="primary">{{
            scope.row.proCode
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column
        label="商品名称"
        align="center"
        prop="proName"
        fixed="left"
        width="150"
      >
      </el-table-column>
      <el-table-column label="商品单位" align="center" prop="unitName" />
      <!-- <el-table-column label="商品成本" align="center" prop="cost" /> -->
      <el-table-column
        label="销售底价"
        align="center"
        prop="price"
        width="100"
      />
      <el-table-column label="商品类别" align="center" prop="typeName" />
      <el-table-column
        label="商品备注"
        align="left"
        prop="proRemark"
        width="150"
      >
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            width="120"
            trigger="hover"
            :content="scope.row.proRemark"
          >
            <div slot="reference" class="ellipsis-text">
              {{ scope.row.proRemark }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="modifyBy" />
      <el-table-column
        label="修改时间"
        align="center"
        prop="modifyDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basedata:goods:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            disabled
            v-hasPermi="['basedata:goods:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        :disabled="formDisabled"
      >
        <el-form-item label="商品编号" prop="proCode">
          <el-input
            :value="form.proCode"
            placeholder="请输入商品编号"
            disabled
          />
        </el-form-item>
        <el-form-item label="商品名称" prop="proName">
          <el-input v-model="form.proName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品单位" prop="unitId">
          <el-select v-model="form.unitId" placeholder="请选择商品单位">
            <el-option
              :label="unit.unitName"
              :value="unit.id"
              v-for="unit in unitList"
              :key="unit.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择商品分类">
            <el-option
              :label="type.typeName"
              :value="type.id"
              v-for="type in typeList"
              :key="type.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售底价" prop="price">
          <el-input
            v-model="form.price"
            placeholder="请输入销售底价"
            @blur="checkPrice"
          />
        </el-form-item>
        <el-form-item label="商品备注" prop="proRemark">
          <el-input
            type="textarea"
            v-model="form.proRemark"
            placeholder="请输入商品备注"
          />
        </el-form-item>
        <i
          class="el-icon-arrow-down"
          @click="showFormDetail"
          style="cursor: pointer"
        ></i>
        <el-divider></el-divider>
        <div v-show="formDetailDisabled">
          <!-- <el-form-item label="商品成本" prop="cost">
            <el-input :value="form.cost" placeholder="" disabled />
          </el-form-item> -->
          <el-form-item label="创建人" prop="createBy">
            <el-input :value="form.createBy" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="创建时间" prop="createDate">
            <el-date-picker
              clearable
              v-model="form.createDate"
              type="date"
              disabled
              value-format="yyyy-MM-dd"
              placeholder=""
            />
          </el-form-item>
          <el-form-item label="修改人" prop="modifyBy">
            <el-input :value="form.modifyBy" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="修改时间" prop="modifyDate">
            <el-date-picker
              clearable
              v-model="form.modifyDate"
              type="date"
              disabled
              value-format="yyyy-MM-dd"
              placeholder=""
            />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
} from "@/api/basedata/goods";
import { listAllType } from "@/api/basedata/type";
import { listUnitAll } from "@/api/basedata/unit";

export default {
  name: "Goods",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 商品备注时间范围
      daterangeCreateDate: [],
      // 商品备注时间范围
      daterangeModifyDate: [],
      // 表单禁用
      formDisabled: false,
      //表单详细信息控制
      formDetailDisabled: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        proCode: null,
        proName: null,
        typeId: null,
        createDate: null,
        modifyDate: null,
      },
      unitList: [],
      typeList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        proCode: [
          { required: true, message: "商品编号不能为空", trigger: "blur" },
        ],
        proName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "blur",
          },
        ],
        unitId: [
          { required: true, message: "商品单位不能为空", trigger: "change" },
        ],
        typeId: [
          { required: true, message: "商品类别不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getTypeAll();
    this.getUnitList();
  },
  methods: {
    // 获取所有单位
    getUnitList() {
      listUnitAll().then((response) => {
        this.unitList = response.data;
        console.log(this.unitList);
      });
    },

    /** 查询商品列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateDate && "" != this.daterangeCreateDate) {
        this.queryParams.params["beginCreateDate"] =
          this.daterangeCreateDate[0];
        this.queryParams.params["endCreateDate"] = this.daterangeCreateDate[1];
      }
      if (null != this.daterangeModifyDate && "" != this.daterangeModifyDate) {
        this.queryParams.params["beginModifyDate"] =
          this.daterangeModifyDate[0];
        this.queryParams.params["endModifyDate"] = this.daterangeModifyDate[1];
      }
      listGoods(this.queryParams).then((response) => {
        this.goodsList = response.rows;
        console.log(this.goodsList);
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取所有商品分类 */
    getTypeAll() {
      listAllType().then((response) => {
        this.typeList = response.data;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        proCode: null,
        proName: null,
        unitId: null,
        price: null,
        typeId: null,
        proRemark: null,
        createBy: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
        isDel: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateDate = [];
      this.daterangeModifyDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.formDisabled = false;
      this.form.proCode = "SP" + Date.now();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getGoodsInfo(row);
      this.open = true;
      this.title = "修改商品";
      this.formDisabled = false;
    },
    //获取商品信息
    getGoodsInfo(row) {
      const id = row.id || this.ids;
      getGoods(id).then((response) => {
        this.form = response.data;
      });
    },
    //展示商品详情
    showGoodsInfo(row) {
      this.title = "商品详情";
      this.open = true;
      this.formDisabled = true;
      this.getGoodsInfo(row);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商品编号为"' + ids + '"的数据项？')
        .then(function () {
          return delGoods(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "basedata/goods/export",
        {
          ...this.queryParams,
        },
        `goods_${new Date().getTime()}.xlsx`
      );
    },

    /**
     * 校验销售低价
     */
    checkPrice() {
      if (this.form.price == null || this.form.price == "") {
        this.form.price = null;
        return;
      }
      if (isNaN(this.form.price)) {
        this.$message.error("请输入数字");
        this.form.price = null;
        return false;
      }
      let value = parseFloat(this.form.price);
      if (value < 0) {
        this.$message.error("金额不能小于0");
        this.form.price = null;
      } else if (value > 9999999) {
        this.$message.error("金额不能大于9999999");
        this.form.price = null;
      } else {
        // 四舍五入并保留两位小数
        value = value.toFixed(2);

        // 更新金额字段为格式化后的值
        this.form.price = value;
      }
    },
    // 显示表单详细信息
    showFormDetail() {
      this.formDetailDisabled = !this.formDetailDisabled;
    },
  },
};
</script>
<style scoped>
/**  长度过长的文本省略号 */
.ellipsis-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 120px;
}
</style>
